import { Button } from 'antd'
import { useSelector, useDispatch } from 'react-redux'

import style from './style.module.scss'

import { parseJsonByString } from '../../../common/utils'
import AreaList from './component/area-list'
import { getChangeSchemaAction } from './store/action'
import axios from 'axios'

const useStore = () => {
  const dispatch = useDispatch()
  const schema = useSelector((state) => state.homeManagement.schema)
  const changeSchema = (schema) => {
    dispatch(getChangeSchemaAction(schema))
  }
  return {
    changeSchema,
    schema
  }
}

const HomeManagement = () => {
  const { changeSchema, schema } = useStore()

  const handleSaveBtnClick = () => {
    const { token } = window.localStorage
    axios.post(
      '/api/schema/save',
      { schema: JSON.stringify(schema) },
      {
        headers: { token }
      }
    )
  }
  const handleResetBtnClick = async () => {
    const res = await axios.get('/api/schema/getLatestOne')
    const data = res.data?.data
    data && changeSchema(parseJsonByString(data.schema, {}))
  }

  return (
    <div>
      <AreaList children={schema.children || []} />
      <div className={style.save}>
        <Button type="primary" onClick={handleSaveBtnClick}>
          保存区块配置
        </Button>
        <Button
          className={style.reset}
          type="primary"
          onClick={handleResetBtnClick}
        >
          重置区块配置
        </Button>
      </div>
    </div>
  )
}

export default HomeManagement
